<?php

namespace app\modules\admin\controllers;

use app\models\AgentProfit;
use app\models\Card;
use app\models\ManagerLog;
use app\models\UserCardRecharge;
use app\models\UserCardReserveRecharge;
use app\models\Agent;
use app\models\AgentBill;
use app\models\AgentPackage;
use app\models\Payment;
use app\models\CommissionBill;
use app\models\CardDatalog;
use app\models\Package;
use Exception;
use Yii;
use yii\data\Pagination;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\db\Expression;
/**
 * 财务管理
 * Class FinanceController
 * @package app\modules\admin\controllers
 */
class MessageController extends BaseController
{   
    /**
     * 用户卡充值列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionUserCardRechargeList()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $start_time = strtotime($current_time);
        $end_time = $start_time + 86399;
        $query = UserCardRecharge::find()->alias('recharge');
        $query->joinWith('user user');
        $query->joinWith('agent agent');
        $query->joinWith('card card');
        $query->joinWith('packages packages');
        $query->andFilterWhere(['like', 'user.username', $this->get('search_username')]);
        $query->andFilterWhere(['like','agent.username',$this->get('search_agentname')]);
        $query->andFilterWhere(['like','card.iccid', $this->get('search_iccid')]);
        $query->andFilterWhere(['like','trade_type',$this->get('search_trade_type')]);
        $query->andFilterWhere(['like','recharge_type',$this->get('search_recharge_type')]);
        $query->andFilterWhere(['source'=> $this->get('search_source')]);
        $query->andFilterWhere(['recharge.id'=>$this->get('search_id')]);
        $query->andFilterWhere(['is_show'=>1]);
        if(!$current_time){
            $query->andFilterWhere(['recharge.create_time'=> '']);
        }else{
            $query->andFilterWhere(['between','recharge.create_time',$start_time,$end_time]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('recharge.create_time DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $rechargeList = $query->all();

        return $this->render('user_card_recharge_list', [
            'rechargeList' => $rechargeList,
            'pagination' => $pagination,
            'current_time' => $current_time
        ]);
    }

    /**
     * 卡充值详情
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionRechargeView()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $recharge = UserCardRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            throw new NotFoundHttpException('没有找到充值信息。');
        }

        return $this->render('recharge_view', [
            'recharge' => $recharge,
        ]);
    }

    /**
     * 设置充值已支付AJAX接口
     * @return array
     * @throws BadRequestHttpException
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionSetRechargePaid()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $recharge = UserCardRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            throw new NotFoundHttpException('没有找到充值信息。');
        }
        if ($recharge->status != UserCardRecharge::STATUS_WAIT_PAY) {
            throw new BadRequestHttpException('充值状态异常，不能设置为已支付。');
        }

        $trans = Yii::$app->db->beginTransaction();
        try {
            $recharge->setPaid();

            $trans->commit();

            ManagerLog::info($this->manager->id, '设置充值已支付', $recharge->id);

            return [];
        } catch (Exception $e) {
            try {
                $trans->rollBack();
            } catch (Exception $_) {
            }
            return ['error' => 'SERVER', 'message' => $e->getMessage()];
        }
    }

    /**
     * 增加卡时长AJAX接口
     * @return array
     * @throws BadRequestHttpException
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionAddRechargeTerm()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $recharge = UserCardRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            throw new NotFoundHttpException('没有找到充值信息。');
        }
        if ($recharge->status != UserCardRecharge::STATUS_PAID) {
            throw new BadRequestHttpException('充值状态异常，不能增加套餐时长。');
        }

        $card = Card::findOne(['id' => $recharge->card_id]);
        if ($card->package_id != $recharge->package_id) {
            return ['error' => 'SERVER', 'message' => '充值套餐和卡套餐不匹配。'];
        }
        if ($card->term_length_unit != $recharge->term_length_unit) {
            return ['error' => 'SERVER', 'message' => '充值有效期单位和卡套餐有效期单位不匹配。'];
        }
        if ($card->status == Card::STATUS_DEACTIVATED && $card->term_end_time < time()) { // 卡已经停用且超过有效期了
            // 接口激活
            try {
                $card->setStatus(Card::STATUS_ACTIVATED);
            } catch (Exception $e) {
                Yii::warning('激活卡时接口错误：' . $e->getMessage());
                Yii::warning($e->getTraceAsString());
                return ['error' => 'SERVER', 'message' => '激活卡时接口错误：' . $e->getMessage()];
            }
            // 更新当前时间为激活时间
            $card->updateAttributes(['active_time' => time(), 'status' => Card::STATUS_ACTIVATED]);
            $card->term_length = $recharge->term_length;
            $card->calcTermEnd();
        } elseif ($card->status == Card::STATUS_ACTIVATED) { // 卡已经激活
            // 增加时长并重新计算有效期
            $card->updateCounters(['term_length' => $recharge->term_length]);
            $card->calcTermEnd();
        }
        $recharge->updateAttributes(['status' => UserCardRecharge::STATUS_RECHARGE, 'update_time' => time()]);

        return [];
    }
    /**
     * 用户卡预充值列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionUserCardReserveRechargeList()
    {
        if (!$this->manager->can('finance/user-card-reserve-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $start_time = strtotime($current_time);
        $end_time = $start_time + 86399;
        $query = UserCardReserveRecharge::find()->alias('recharge');
        $query->joinWith('user user');
        $query->joinWith('agent agent');
        $query->joinWith('card card');
        //$query->andFilterWhere(['like', 'user.username', $this->get('search_username')]);
        $query->andFilterWhere(['like','agent.username',$this->get('search_agentname')]);
        //$query->andFilterWhere(['recharge.status' => $this->get('search_status')]);
        $query->andFilterWhere(['like','card.iccid',$this->get('search_iccid')]);
        $query->andFilterWhere(['source'=> $this->get('search_source')]);
        $query->andFilterWhere(['execute_status' => $this->get('search_status')]);
        if(!$current_time){
            $query->andFilterWhere(['recharge.create_time'=> '']);
        }else{
            $query->andFilterWhere(['between','recharge.create_time',$start_time,$end_time]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('recharge.create_time DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $rechargeList = $query->all();

        return $this->render('user_card_reserve_recharge_list', [
            'rechargeList' => $rechargeList,
            'pagination' => $pagination,
            'current_time' => $current_time
        ]);
    }
    /**
     * 卡预充值详情
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionReserveRechargeView()
    {
        if (!$this->manager->can('finance/user-card-reserve-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $recharge = UserCardReserveRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            throw new NotFoundHttpException('没有找到充值信息。');
        }

        return $this->render('reserve_recharge_view', [
            'recharge' => $recharge,
        ]);
    }
    /**
     * 代理商收益列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionAgentProfit()
    {
        if (!$this->manager->can('finance/agent-profit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $query = AgentProfit::find()->alias('profit');
        $query->joinWith('agent agent');
        $query->joinWith('recharge recharge');
        $query->joinWith('package package');
        $query->andFilterWhere(['agent.username' => $this->get('search_agent')]);
        $query->andFilterWhere(['profit.source' => $this->get('search_source')]);
        $query->andFilterWhere(['profit.is_show'=>1]);
        $query->andFilterWhere(['profit.profit_type'=>1]);
        if(!$current_time){
            $query->andFilterWhere(['profit.same_time'=> '']);
        }else{
            $query->andFilterWhere(['profit.same_time' => strtotime($this->get('search_time'))]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('profit.id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $profitList = $query->all();

        return $this->render('agent_profit_list', [
            'profitList' => $profitList,
            'pagination' => $pagination,
            'current_time' => $current_time,
        ]);
    }
    /**
     * 代理商激活奖励列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionActiveReward(){
        if (!$this->manager->can('finance/agent-profit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $query = AgentProfit::find()->alias('profit');
        $query->joinWith('agent agent');
        $query->joinWith('recharge recharge');
        $query->joinWith('package package');
        $query->joinWith('card card');
        $query->andFilterWhere(['agent.username' => $this->get('search_agent')]);
        $query->andFilterWhere(['profit.source' => $this->get('search_source')]);
        $query->andFilterWhere(['profit.profit_type'=>2]);
        $query->andFilterWhere(['profit.is_show'=>1]);
        if(!$current_time){
            $query->andFilterWhere(['profit.same_time'=> '']);
        }else{
            $query->andFilterWhere(['profit.same_time' => strtotime($this->get('search_time'))]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('profit.create_time DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $profitList = $query->all();
        $pay_type = '2';
        return $this->render('active_reward_list', [
            'profitList' => $profitList,
            'pagination' => $pagination,
            'current_time' => $current_time,
            'pay_type'   => $pay_type
        ]);
    }
    //支付分成佣金
    public function actionSetPaymentPaid(){
		$data['id'] = $this->get('id');
        $data['agent_id'] = $this->get('agentid');
        $data['amount'] = $this->get('money');
        $data['description'] = '分润';
        $data['pay_type'] = $this->get('pay_type');
        $agent = Agent::findOne(['id' => $this->get('agentid')]);
        $username = $agent['username'];
        $urls = "http://test.0539club.cn/index.php?g=Wap&m=IotCard&a=getWechatid"."&username=".$username;
        $result = $this->getUrl($urls);
        $arr = json_decode($result,true);
        $data['userid'] = $arr['wechat_id'];
        $data['name'] = $agent['username'];
        $url = "http://test.0539club.cn/index.php?g=Wap&m=CiotCard&a=transfers2";
        $results = $this->curl_post($url,$data);
        $pay_code = json_decode($results,true);
        if($pay_code['code'] == 1){
            Yii::$app->db->createCommand()->update('commission_bill', ['pay_status' => 2], 'id = :id',['id' => $this->get('id')], 'agent_id = :agent_id',['agent_id' => $this->get('agentid')], 'generate_time = :generate_time',['generate_time' => $this->get('gtime')])->execute(); 
            return [];
        }else{
            return ['error' => 'SERVER', 'message' => $pay_code['msg']];
        }
             
    }
    //支付激活奖励
    public function actionSetActivePaymentPaid(){
        $data['id'] = $this->get('id');
        $data['agent_id'] = $this->get('agentid');
        $data['amount'] = $this->get('money');
        $data['description'] = '激活奖励';
        $data['pay_type'] = $this->get('pay_type');
        $agent = Agent::findOne(['id' => $this->get('agentid')]);
        $username = $agent['username'];
        $urls = "http://test.0539club.cn/index.php?g=Wap&m=IotCard&a=getWechatid"."&username=".$username;
        $result = $this->getUrl($urls);
        $arr = json_decode($result,true);
        $data['userid'] = $arr['wechat_id'];
        $data['name'] = $agent['username'];
        $url = "http://test.0539club.cn/index.php?g=Wap&m=CiotCard&a=transfers2";
        $results = $this->curl_post($url,$data);
        $pay_code = json_decode($results,true);
        if($pay_code['code'] == 1){
            Yii::$app->db->createCommand()->update('agent_profit', ['pay_status' => 2], 'id = :id',['id' => $this->get('id')], 'agent_id = :agent_id',['agent_id' => $this->get('agentid')], 'same_time = :same_time',['same_time' => $this->get('gtime')])->execute(); 
            return [];
        }else{
            return ['error' => 'SERVER', 'message' => $pay_code['msg']];
        }
           
    }
    //代理商付款记录
    public function actionPaymentList(){

        if (!$this->manager->can('finance/payment-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $query = Payment::find()->alias('pay');
        $query->andFilterWhere(['name'=>$this->get('search_agent')]);
        if(!$current_time){
            $query->andFilterWhere(['payment_time'=> '']);
        }else{
           $query->andFilterWhere(['time' => strtotime($this->get('search_time'))]); 
        } 
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('pay.id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $paymentList = $query->all();

        return $this->render('payment_list', [
            'paymentList' => $paymentList,
            'pagination' => $pagination,
            'current_time' => $current_time,
        ]);
    }
    //代理商佣金列表
    public function actionAgentCommission(){
        $query = strtotime($this->get('search_time'));
        $query = CommissionBill::find()->alias('bill');
        $query->andFilterWhere(['agentname'=> $this->get('search_username')]);
        if(!$this->get('search_time')){
            $query->andFilterWhere(['bill.generate_time'=> '']);
        }else{
           $query->andFilterWhere(['bill.generate_time' => strtotime($this->get('search_time'))]); 
        }
        $query->andFilterWhere(['pay_status'=>$this->get('search_status')]);
        $query->andFilterWhere(['bill.id'=>$this->get('search_id')]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy(['id'=>SORT_DESC]);
        $query->offset($pagination->offset)->limit($pagination->limit);
        $billList = $query->all();
        $pay_type = '2';
        return $this->render('agent_commission_list',[
            'billList' => $billList,
            'pagination' => $pagination,
            'pay_type' => $pay_type
        ]);
    }
    //代理商佣金生成账单
    public function actionGenerateAgentBill(){
        $date = strtotime($this->get('day'));
        $profitList = (new \yii\db\Query())
        ->select(['agent_profit.id as id','agent.id as agent_id','agent.username as username','agent_profit.comm_type as comm_type','sum(agent_profit.money) as sum_money','agent_profit.create_time as create_time','sum(agent_profit.pay_status) as sum_count'])
        ->from('agent_profit')
        ->join('join','agent','agent_profit.agent_id=agent.id')
        ->groupBy('agent_profit.agent_id')
        ->andFilterWhere(['same_time'=>$date])
        ->andFilterWhere(['is_show'=>1])
        ->andFilterWhere(['<>','agent_profit.money',0])
        ->andFilterWhere(['profit_type'=>1])
        ->all();
        if(!$profitList){
            return ['error' => 'EMPTY', 'message' => '所选日期无收益记录，生成账单失败！'];
        }
        foreach($profitList as $key=>$value){
            $bill = new CommissionBill();
            $bill->agent_id = $profitList[$key]['agent_id'];
            $bill->generate_time = strtotime(date('Y-m-d',$date));
            $bill->money = $profitList[$key]['sum_money'];
            $bill->create_time = time();
            $bill->agentname = $profitList[$key]['username'];
            $bill->count = $profitList[$key]['sum_count'];
			$bill->comm_type = $profitList[$key]['comm_type'];
            $bill->save();
        }

        $result = CommissionBill::find()
            ->andWhere(['generate_time' => $date])
            ->asArray()
            ->select([
                'agent_id' => 'agent_id', 
                'bill_id'  => 'id',
                'money' => new Expression('sum(money)'),
                'amount' => 'count',
            ])
            ->groupBy('agent_id')
            ->all();
        foreach ($result as $key=>$value){
            $agentBill = new AgentBill();
            $agentBill->agent_id = $result[$key]['agent_id'];
            $agentBill->bill_id  = $result[$key]['bill_id'];
            $agentBill->day = date('Y-m-d',$date);
            $agentBill->pay_count = $result[$key]['amount'];
            $agentBill->money = $result[$key]['money'];
            $agentBill->status = 1;
            $agentBill->save();
        }
        return [];
    }
    
     //执行预充值
    public function actionSetReserveRechargeExecute(){
        $id = $this->get('id');
        $order_sn = date('YmdHis').rand(1000, 9999);
        $reserve = UserCardReserveRecharge::findOne(['id'=>$id]);
        $datas['card']['iccid'] = $reserve->iccid;
        $datas['term_length'] = $reserve->term_length;
        $datas['price'] = $reserve->price;
        $datas['money'] = $reserve->money;
        $datas['trade_type'] = $reserve->trade_type;
        $datas['trade_no'] = $order_sn;
        $datas['trade_id'] = $order_sn;//交易编号
        $datas['app_id'] = "weixin";
        $datas['uid'] = $reserve->uid;
        $datas['agent_id'] = $reserve->agent_id;
        $datas['package_id'] = $reserve->package_id;
        $datas['term_length_unit'] = $reserve->term_length_unit;
        $datas['source'] = $reserve->source;
        $datas['card_recharge_id'] = $reserve->card_recharge_id;
        $data_string = json_encode($datas);
        $getMoneyUrl="http://cu.ly186.cn/api/card/agent-reserve-recharge?version=1.0.0&app_id=weixin&nonce=123456&timestamp=1&sign=0123456789abcdef&token=";
        $iot_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MzU4MTM2NzYsInVpZCI6NCwiYXBwIjoid2VpeGluIn0=.6428835f2b1518367de235f6bd044eb41ae995f9b13dfe289faeb8448f6ce16f";
        $getMoneyUrl = $getMoneyUrl.$iot_token;
        $result = $this->UrlPost($getMoneyUrl,$data_string);
        $results = json_decode($result,true);
        if($results['error'] == ''){
            Yii::$app->db->createCommand()->update('user_card_reserve_recharge', ['execute_status' => 1], 'id = :id',['id' => $reserve['id']])->execute(); 
            //ManagerLog::info($this->manager->id, '手动执行预充值', print_r($reserve->attributes, true));
            return [];
        }else{
            return ['error' => 'SERVER','message' => '执行失败'];
        }
             
    }
    public function actionSetRechargeStatusA(){
        $id = $this->get('id');
        Yii::$app->db->createCommand()->update('user_card_recharge', ['recharge_type' => 1], 'id = :id',['id' => $id])->execute(); 
            return [];

    }
    public function actionSetRechargeStatusB(){
        $id = $this->get('id');
        Yii::$app->db->createCommand()->update('user_card_recharge', ['recharge_type' => 2], 'id = :id',['id' => $id])->execute(); 
            return [];

    }
    public function actionSetRechargeStatusC(){
        $id = $this->get('id');
        Yii::$app->db->createCommand()->update('user_card_recharge', ['recharge_type' => 3], 'id = :id',['id' => $id])->execute(); 
            return [];

    }
    public function actionSetRechargeStatusD(){
        $id = $this->get('id');
        Yii::$app->db->createCommand()->update('user_card_recharge', ['recharge_type' => 4], 'id = :id',['id' => $id])->execute(); 
            return [];

    }

    public function UrlPost($url,$data_string){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
    function curl_post($url,$data_string){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }

    public function getUrl($url){
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        //$data = curl_exec($curl);
        $response = curl_exec($curl);

        if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {
            list($header, $body) = explode("\r\n\r\n", $response, 2);
        }
        //关闭URL请求
        curl_close($curl);
        //return json_decode($data,TRUE);
        return $body;
    }

    /**
     * 用户卡充值列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionUserCardRechargeLists()
    {
        
        $current_time = $this->get('search_time');
        $start_time = strtotime($current_time);
        $end_time = $start_time + 86399;
        $query = UserCardRecharge::find()->alias('recharge');
        $query->joinWith('user user');
        $query->joinWith('agent agent');
        $query->joinWith('card card');
        $query->joinWith('packages packages');
        $query->andFilterWhere(['like', 'user.username', $this->get('search_username')]);
        $query->andFilterWhere(['like','agent.username',$this->get('search_agentname')]);
        $query->andFilterWhere(['like','card.iccid', $this->get('search_iccid')]);
        $query->andFilterWhere(['like','trade_type',$this->get('search_trade_type')]);
        $query->andFilterWhere(['like','recharge_type',$this->get('search_recharge_type')]);
        $query->andFilterWhere(['source'=> $this->get('search_source')]);
        $query->andFilterWhere(['recharge.id'=>$this->get('search_id')]);
        $query->andFilterWhere(['is_show'=>1]);
        if(!$current_time){
            $query->andFilterWhere(['recharge.create_time'=> '']);
        }else{
            $query->andFilterWhere(['between','recharge.create_time',$start_time,$end_time]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('recharge.create_time DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $rechargeList = $query->all();

        return $this->render('user_card_recharge_lists', [
            'rechargeList' => $rechargeList,
            'pagination' => $pagination,
            'current_time' => $current_time
        ]);
    }
    /**
     * 消息推送
     * @return string
     * @throws ForbiddenHttpException
     * 1，筛选5天内到期的  每天提醒一次
     * 2，筛选剩余流量不足20%一次  剩余10%一次 5%一次 用尽一次
     * ->createCommand()->rawSql
     */
    public function actionPushMessage()
    {

        $search_day = $this->get('search_day');
        $search_flow = $this->get('search_flow');
        $query = Card::find()->alias('card');
        $now_time = time();
        if(!empty($search_day)){
            $whereday = "term_end_time-$now_time<=$search_day*86400 and term_end_time-$now_time>0";
        }else{
            $whereday = "term_end_time-$now_time<=2*86400 and term_end_time-$now_time>0";
        }
        if(!empty($search_flow)){
            if($search_flow>1){
                $flow =$search_flow/100;
            }else{
                $flow =  $search_flow;
            }
            $whereflow = $whereday." and (1-(data/total_flow))<=$flow";
        }else{
            $whereflow = $whereday." and (1-(data/total_flow))<=0.2";
        }
        $query->where($whereflow);
        $query->andFilterWhere(['status'=> '4']);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->offset($pagination->offset)->limit($pagination->limit);
        $list = $query->all();
        return $this->render('push_message', [
            'list'=>$list,
            'pagination' => $pagination
        ]);
    }
    /**
     * 消息推送
     * @return string
     * @throws ForbiddenHttpException
     * 1，筛选5天内到期的  每天提醒一次
     * 2，筛选剩余流量不足20%一次  剩余10%一次 5%一次 用尽一次
     * ->createCommand()->rawSql
     */
    public function actionDoPushMessage()
    {
        $search_day = $this->get('search_day');
        $search_flow = $this->get('search_flow');
        $query = Card::find()->alias('card');
        $now_time = time();
        if(!empty($search_day)){
            $whereday = "term_end_time-$now_time<=$search_day*86400 and term_end_time-$now_time>0";
        }else{
            $whereday = "term_end_time-$now_time<=2*86400 and term_end_time-$now_time>0";
        }
        if(!empty($search_flow)){
            if($search_flow>1){
                $flow =$search_flow/100;
            }else{
                $flow =  $search_flow;
            }
            $whereflow = $whereday." and (1-(card.data/total_flow))<=$flow";
        }else{
            $whereflow = $whereday." and (1-(card.data/total_flow))<=0.2";
        }

        $query->select('card.iccid,package.name as pname,card.term_end_time,card.total_flow,card.data,card.open_id');
        $query->where($whereflow);
        $query->andFilterWhere(['card.status'=> '4']);
        $query->joinWith('package package');
        $list = $query->all();
        foreach($list as $key=>$val){
            $lists[$key+1]['iccid']=$val['iccid'];
            $lists[$key+1]['name']=$val['pname'];
            $lists[$key+1]['term_end_time']=date('Y-m-d H:i:s',$val['term_end_time']);
            $lists[$key+1]['total_flow']=($val['total_flow']/1073741824)."G";
            $lists[$key+1]['data']=round(($val['total_flow']-$val['data'])/1073741824,2)."G";
            $lists[$key+1]['open_id']=$val['open_id'];
        }
        $json  = json_encode($lists);
        //$json = '{"1":{"iccid":"89860619130013025000","name":"VIP\u5b9a\u5236\u5361(\u94ed\u4fe1)","term_end_time":"2020-04-17 23:59:59","total_flow":"100G","data":"8.53G","open_id":null},"2":{"iccid":"89860619130012601220","name":"VIP\u5b9a\u5236\u5361(\u94ed\u4fe1)","term_end_time":"2020-04-16 23:59:59","total_flow":"100G","data":"11.4G","open_id":null}}';
        $url = "http://wx.ly186.cn/index.php?g=Wap&m=CiotMessage&a=topushmessage";
        $json = json_decode($json,true);
        $json = json_encode($json,true);
        /*echo "<pre>";
        print_r($json);exit;*/
        echo $this->curlRequest($url,$json);
        //exit;
        return $this->render('send_success', [
            'list'=>"",
            'pagination' => ""
        ]);


    }
    /**
     * curl
     */
    public function curlRequest($url,$data=null){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
        if(!empty($data)){
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        }

        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    
}
